package com.xca.znb.view;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.xca.znb.R;
import com.xca.znb.entity.Cart;
import com.xca.znb.entity.Goods;
import com.xca.znb.entity.User;
import com.xca.znb.model.impl.CartEndPayImpl;
import com.xca.znb.presenter.CartEndPayPresenter;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class EndPayCart extends AppCompatActivity {
    private ImageButton backBtn ;
    private TextView needPay , balanceNum , toRecharge ;
    Button payMoney;
    private ArrayList<Integer> idList = new ArrayList<>();
    private CartEndPayPresenter presenter ;
    private List<Cart> cartList = new ArrayList<>();
    private List<Goods> goodsList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_end_pay_cart);
        initView();

        CartEndPayImpl cartEndPayImpl = new CartEndPayImpl(this);
        presenter = new CartEndPayPresenter(cartEndPayImpl);
        if (getIntent().getExtras() != null) {
            // 使用Serializable方式获取ArrayList
            idList = (ArrayList<Integer>) getIntent().getSerializableExtra("toEndPayCartList");
        }
        Intent intent = getIntent() ;
        int localId = intent.getIntExtra("toEndPayCartLocal" , 0);

        SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
        String phone = sharedPreferences.getString("phone" , "");

        //获取当前时间：精确到秒
        LocalDateTime nowTime = LocalDateTime.now();
        String secTime = nowTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String dayTime = nowTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        double needPayNumber = 0 ;
        //获取cartList
        for (int cartId : idList){
            Cart cart = presenter.getCartById(cartId);
            cartList.add(cart);
            Goods goods = presenter.getGoodsById(cart.getGoodsId());
            needPayNumber = needPayNumber + (goods.getPrice()*cart.getNum());
            goodsList.add(goods);
        }
        needPay.setText(String.valueOf(needPayNumber));

        User user = presenter.getUserByPhone(phone);


        double finalNeedPayNumber = needPayNumber;
        payMoney.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (presenter.getBalance(phone) >= finalNeedPayNumber){
                    String buyerAccountType = "购买" ;
                    String salesAccountType = "出售";
                    AlertDialog.Builder builder = new AlertDialog.Builder(EndPayCart.this);
                    builder.setMessage("请输入支付密码");
                    final EditText editText = new EditText(EndPayCart.this);
                    editText.setHint("输入在此处");
                    builder.setView(editText);
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            String inputPassword = editText.getText().toString().trim();
                            if (inputPassword.equals(user.getPay_password())){
                                for (Cart cart : cartList){
                                    new Handler().postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            Goods goods = presenter.getGoodsById(cart.getGoodsId());
                                            boolean isAdd = presenter.addOrder(localId,goods.getId(),cart.getNum(),"",phone,goods.getPublisher(),"待发货",secTime);
                                            if (isAdd){
                                                presenter.insertAccount(phone,goods.getPrice()*cart.getNum() , buyerAccountType , dayTime,secTime);
                                                presenter.insertAccount(goods.getPublisher(),goods.getPrice()*cart.getNum(),salesAccountType,dayTime,secTime);
                                                balanceNum.setText(String.valueOf(presenter.getBalance(phone) - finalNeedPayNumber));
                                            }else {
                                                Toast.makeText(EndPayCart.this, "支付失败", Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    },500);
                                }
                                finish();
                            }else {
                                Toast.makeText(EndPayCart.this, "密码错误", Toast.LENGTH_SHORT).show();
                            }
                        }

                    });
                    builder.setNegativeButton("取消",null);
                    builder.create().show();

                }else {
                    Toast.makeText(EndPayCart.this, "余额不足，请充值", Toast.LENGTH_SHORT).show();
                }
            }
        });


        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        toRecharge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(EndPayCart.this , MyAssetsActivity.class);
                startActivity(intent1);
            }
        });
    }

    private void refreshMoney(){
        SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
        String phone = sharedPreferences.getString("phone" , "");

        double needPayNumber = 0 ;
        //获取cartList
        for (int cartId : idList){
            Cart cart = presenter.getCartById(cartId);
            Goods goods = presenter.getGoodsById(cart.getGoodsId());
            needPayNumber = needPayNumber + (goods.getPrice()*cart.getNum());
            goodsList.add(goods);
        }
        needPay.setText(String.valueOf(needPayNumber));
        double balance = presenter.getBalance(phone);
        balanceNum.setText(String.valueOf(balance));
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshMoney();
    }

    private void initView(){
        backBtn = findViewById(R.id.cart_pay_back);
        needPay = findViewById(R.id.cart_pay_money) ;
        balanceNum = findViewById(R.id.cart_pay_balance_money);
        toRecharge = findViewById(R.id.cart_pay_to_recharge);
        payMoney = findViewById(R.id.cart_pay_sure_btn) ;
    }
}